import paho.mqtt.client as mqtt
from threading import Thread
import time 
import json
import schedule
import datetime
import threading

from spec import *
# from temp import *
from cam import *
from app import *
from ftp import *
from config import *

period=0
config_file = './wt.yaml'
config = get_yaml_data(config_file)

spec_run = False
temp_run = False
came_run = False

MQTTHOST = "121.40.144.89"
MQTTPORT = 1883
mqttClient = mqtt.Client()
My_ID = Get_ID()
def shell_thread(cmd):
    print(cmd)
    mqttClient.publish("statue/",'{}\n{}'.format(My_ID,cmd))
    dbg_echo=shell_run(cmd)
    mqttClient.publish("statue/",'{}\n{}'.format(My_ID,dbg_echo))
    # print('shell done')

def time_in_range(start,end):

    d_time = datetime.datetime.strptime(str(datetime.datetime.now().date()) + start, '%Y-%m-%d%H:%M')
    d_time1 = datetime.datetime.strptime(str(datetime.datetime.now().date()) + end, '%Y-%m-%d%H:%M')
    n_time = datetime.datetime.now()
    if n_time > d_time and n_time < d_time1:
        return True
    else:
        return False
def camera_time(time_list):
    for it in time_list:
        # print(it)
        # setting_time = datetime.datetime.strptime(str(datetime.datetime.now().date()) + it, '%Y-%m-%d%H:%M')
        if (it==time.strftime("%H:%M", time.localtime())):
            # print("cam...")
            # print('>:',it)
            return True
        # else:
            # print('X:',it,time.strftime("%H:%M", time.localtime()))
    return False
def config_update(file,config_dict,config_json):
    if(config_json['dev_id']==My_ID):
        config_dict['time']['specTimeStart']=config_json['specTimeStart']
        config_dict['time']['specTime']=config_json['specTime']
        config_dict['time']['specTimeEnd']=config_json['specTimeEnd']
        config_dict['time']['tempTime']=config_json['tempTime']
        config_dict['time']['camTime']=config_json['camTime'].split(',')
        config_dict['spec']['ver']=config_json['ver']
        # print("update:",config_dict)
        date_time=shell_run('date').strip()
        config_info = {"ID":My_ID,"statue":"config update","time":date_time}
        mqttClient.publish("statue/",json.dumps(config_info))
        save_yame(file,config_dict)
    else:
        print('setting ignore')

def on_mqtt_connect():
    mqttClient.connect(MQTTHOST, MQTTPORT, 60)
    mqttClient.loop_start()
def on_publish(topic, payload, qos):
    mqttClient.publish(topic, payload, qos)
def on_message_come(lient, userdata, msg):

    global config
    # print(msg.topic + " " + ":" + str(msg.payload))
    if(msg.topic=='setting/'):
        config_rec = json.loads(msg.payload)
        # print(config_rec['data'])
        config_update(config_file,config,config_rec['data'])
        # print('update:',config)
        # print('update config')
    elif(msg.topic=='who/'):
        disk_info=shell_run('df -h|grep root').strip()
        up_time=shell_run(' w | grep up').strip()
        i_am_alive = {"ID":My_ID,"statue":disk_info,"up_time":up_time}
        mqttClient.publish("statue/",json.dumps(i_am_alive))
    elif(msg.topic=='dbg/'):
        bash_cmd = json.loads(msg.payload)
        if(bash_cmd['ID']=='*'):
            t1 = Thread(target=shell_thread, args=(bash_cmd['shell'],))
            t1.start()   
        elif(bash_cmd['ID']==My_ID):
            t1 = Thread(target=shell_thread, args=(bash_cmd['shell'],))
            t1.start()
def on_subscribe(topic):
    mqttClient.subscribe(topic, 1)
    mqttClient.on_message = on_message_come # 消息到来处理函数

def spec_task():
    global config
    
    # print('spec_task')
    # 光谱数据
    light_data=read_spec()
    ver = int(config['spec']['ver'])
    light_res = {"ID":My_ID,"ver":str(ver),"light":light_data}
    print(light_res)
    mqttClient.publish("light/",json.dumps(light_res))
def temp_task():
    print('temp_task')
      # air_data = read_temp()
      # air_info={"ID":My_ID,"temp":air_data[0],"hume":air_data[1]}
      # print(air_info)
      # mqttClient.publish("air/", json.dumps(air_info))

def cam_task():
    print('cam_task start..')
    time.sleep(10)
    print('cam_task done..')
    clean_pic()
    file_name = take_picture()
    try:
        ftp_upload(My_ID,'./exe/tmp/',file_name)
    except Exception as e:
        print("<Error> : ",e)
    file_info={"ID":My_ID,"name":file_name}
    mqttClient.publish("file/", json.dumps(file_info))
    



# print(config)


temp_period_count = 0
spec_period_count = 0


def run():
    global temp_run,spec_run,came_run
    global temp_period_count,spec_period_count
    specTimeStart = config['time']['specTimeStart']
    specTime = int(config['time']['specTime'])
    specTimeEnd = config['time']['specTimeEnd']
    camTime = config['time']['camTime']
    tempTime = int(config['time']['tempTime'])
    ver = config['spec']['ver']
    # print('now:',datetime.datetime.now())

    if(temp_period_count%tempTime==0):
        temp_period_count=0
        temp_run =True

    if(spec_period_count%specTime==0):
        spec_period_count=0
       
        if time_in_range(specTimeStart,specTimeEnd):
            spec_run=True
      
    came_run = camera_time(camTime)
    # if flag :
    #     came_run =True

    temp_period_count+=1
    spec_period_count+=1

schedule.every(1).minutes.do(run)

if __name__ == '__main__':
    info_version='version :release 1.2.3 '
    info_author='author  :hdu team'
    print(info_version)
    print(info_author)

    on_mqtt_connect()
    disk_info=shell_run('df -h|grep root').strip()
    info = {"ID":My_ID,"statue:":disk_info,"about":info_version+','+info_author}
    mqttClient.publish("statue/",json.dumps(info))
    on_subscribe("setting/")
    on_subscribe("who/")
    on_subscribe("dbg/")
    

    period=0
    while True:
        schedule.run_pending()  # run_pending：运行所有可以运行的任务
        # print()
        period+=1
        if(period==100):
            period=0
            # print('time up')

            on_mqtt_connect()
            on_subscribe("setting/")
            on_subscribe("dbg/")
            # info = {"ID":My_ID,"statue:":'keep alive'}
            # mqttClient.publish("statue/",json.dumps(info))
        if(temp_run == True):
            temp_run = False
            # print('temp .... ',datetime.datetime.now())
            temp_task()
        if(spec_run == True):
            spec_run = False
            # print('spec .... ',datetime.datetime.now())
            spec_task()
        if(came_run == True ):
            came_run = False
            # print('camera .... ',datetime.datetime.now())
            # cam_task()
            t3 = threading.Thread(target=cam_task)
            t3.start()
        time.sleep(0.1)
